#!/bin/bash
#========================================================================
# Author: YSLin
# Email: 
# File Name: variable.sh
# Description: 
# 	Built-in Variables:
#		FILENAME 	The name of the current input file. 
# 					You should not change the value of this variable.
#		NR 			The number of the current input line or record in 
# 					the input file. You should not change the value of this variable.
#		NF 			The number of fields in the current line or record. 
# 					You should not change the value of this variable.
#		OFS 		The output field separator (default is space).
#		FS 			The input field separator (default is space and tab).
#		ORS 		The output record separator (default is newline).
#		RS 			The input record separator (default is newline).
#   
#	Changing the Input Field Separator
#	1. BEGIN { FS=":" ; }
#	2. awk -F: '{ ... }'
#
#   Allowing awk to Use Shell Variables
#      awk 'script' awkvar1=value awkvar2=value ... files
# Edit History: 
#   2010-12-24    File created.
#========================================================================
#變數像c一樣可以直接assign
echo "hello" | awk ' {fruit="peach"; fruity=fruit; print fruity} '  

#Operator Description
# +       	Add
# -			Subtract
# *			Multiply
# /			Divide
# %			Modulo (Remainder)
# ^			Exponentiation
# += 		Add
# -=		Subtract
# *=		Multiply
# /=		Divide
# %=		Modulo (Remainder)
# ^=		Exponentiation

#算出檔案中所有空白行的數量
for i in `ls` ;
do
	if [ -f "$i" ] ; then
		echo -n "$i"
		#increment the variable x and print it each time a blank line is encountered
		#END會在最後awk都執行完所有actions後,才會執行
		awk '
		/^ *$/ { x+=1 ; }
		END { printf " %s\n",x; }
		' "$i"
	else
		echo "ERROR: $i not a file." >&2
	fi
done

#顯示每一個檔案找到空白行佔整體檔案的比例
for i in `ls` ;
do
	if [ -f "$i" ] ; then
		awk 'BEGIN { printf "%s\t",FILENAME ; }
		/^ *$/ { x+=1 ; }
		END { ave=100*(x/NR) ; printf " %s\t%3.1f\n",x,ave; }
		' "$i"
	else
		echo "ERROR: $i not a file." >&2
	fi
done


#Changing the Input Field Separator
#1. BEGIN { FS=":" ; }
#2. awk -F: '{ ... }'
#使用第2種方法可以讓你用shell script variable來指定
#MYFS=: ; export MYFS ; awk -F${MYFS} '{ ... }'
awk 'BEGIN { FS=":" ; } { print $1 , $6 ; }' /etc/passwd
awk -F: '{ print $1, $6 ; }' /etc/passwd

#Allowing awk to Use Shell Variables
NUMFRUIT="$1"
if [ -z "$NUMFRUIT" ] ; then NUMFRUIT=75 ; fi
awk '
$3 <= numfruit { print ; }
' numfruit="$NUMFRUIT" fruit_prices.txt
